<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <h1>取消请求二</h1>
    <input type="text" id="ipt">
    <button id="btn">提交数据</button>
    <button id="btnO">取消请求</button>

    <script>
        //获取元素
        const oBtn = document.getElementById('btn');
        const btnOne = document.getElementById('btnO');
        const oIpt = document.getElementById('ipt');

        const CancelToken = axios.CancelToken;

        let cancel = null;
        //创建实例化对象
        const myAxios = axios.create({
            baseURL : 'http://127.0.0.1:3000',
            timeout : 10000,
            headers : {}
        })
        // 添加请求拦截器
        myAxios.interceptors.request.use((config)=>{
            return config
        },(err)=>{
            return Promise.reject(err)
        })
        //添加响应拦截器
        myAxios.interceptors.response.use((config)=>{

            return config.data.data
        },(err)=>{
            return Promise.reject(err)
        })

        oBtn.onclick = async function(){
            //获取输入的值
            const iptValue = oIpt.value
            try{
                const re = await myAxios.get('http://127.0.0.1:3000/allAxios',{
                    params:{
                        userId : iptValue
                    },
                    //添加取消请求
                    cancelToken : new CancelToken((c)=>{
                        cancel = c
                    })
                })
                console.log(re);
            }catch(e){
                console.log(e.message);
            }
        };
        //添加取消按钮
        btnOne.onclick = function(){
            cancel()
        }
    </script>
</body>
</html>